﻿using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using System;
using System.Security.Principal;

public class WebFormController : Controller { }

public static class WebFormBrdige
{
    public static void RenderPartial(string partialName)
    {
        RenderPartial(partialName, null);
    }

	public static IPrincipal User
	{
		get
		{
			return HttpContext.Current.User;
		}
	}

    public static void RenderPartial(string partialName, object model)
    {
		HttpContextWrapper httpCtx = new HttpContextWrapper(System.Web.HttpContext.Current);

		RouteData rt = new RouteData();
        rt.Values.Add("controller", "WebFormController");

		ControllerContext ctx = new ControllerContext(new RequestContext(httpCtx, rt), new WebFormController());
        
        IView view = ViewEngines.Engines.FindPartialView(ctx, partialName).View;

		if (view == null)
			throw new Exception("Cannot find the view specificed");

		ViewContext vctx = new ViewContext(ctx, view,
            new ViewDataDictionary { Model = model },
            new TempDataDictionary(),
            System.Web.HttpContext.Current.Response.Output);

        view.Render(vctx, System.Web.HttpContext.Current.Response.Output);
    }

	public static string ActionLink(string linkText, string url)
	{
		return string.Format("<a href=\"{0}\">{1}</a>", url, linkText);
	}

	internal static string ActionLink(string linkText, string url, bool showStyle, string cssClass)
	{
		return string.Format("<a href=\"{0}\" class=\"{2}\">{1}</a>", url, linkText, cssClass);
	}

	public static string ActionLink(string linkText, string actionName, string controllerName)
	{
		return ActionLink(linkText, actionName, controllerName, null);
	}

	public static string ActionLink(string linkText, string actionName, string controllerName, string selectedCssClass)
    {
		string url = RouteTable.Routes.GetVirtualPath(null, new RouteValueDictionary { { "action", actionName }, { "controller", controllerName } }).VirtualPath;

		if (!string.IsNullOrEmpty(selectedCssClass))
		{
			string currentUrl = HttpContext.Current.Request.RawUrl.ToLower().Replace("default.aspx", string.Empty).Replace("?", string.Empty);

			if (url.Equals(currentUrl, StringComparison.InvariantCultureIgnoreCase))
				return ActionLink(linkText, url, true, selectedCssClass);
		}

		return ActionLink(linkText, url);
    }

	public static void MVCTransfer(string path, HttpRequest request)
	{
		path = HttpUtility.UrlDecode(path);
		HttpContext.Current.RewritePath(path, false);
		IHttpHandler httpHandler = new MvcHttpHandler();
		httpHandler.ProcessRequest(HttpContext.Current);
	}
}